//
//  MDHCycleScrollView.swift
//  JSTech
//
//  Created by 华&梅 on 2019/8/5.
//  Copyright © 2020 华&梅. All rights reserved.
//

import UIKit

//MARK: - ==== 枚举
///滑动的方向
@objc public enum MDHScrollDirection: Int {
    ///横向滑动
    case horizontal = 0
    ///垂直滑动
    case vertical   = 1
}
///分页控件的样式
@objc public enum MDHCycleScrollViewPageControlStyle: Int {
    ///系统的控件
    case classic      = 1
    ///推荐一个很好很强大的自定义的 PageControl 轮子：https://github.com/ChiliLabs/CHIPageControl
    ///默认情况
    case jalapeno     = 2
    ///
    case aleppo       = 3
    ///
    case jaloro       = 4
    ///
    case chimayo      = 5
    ///
    case puya         = 6
    ///
    case paprika      = 7
    ///
    case fresno       = 8
    ///
    case aji          = 9
    
    case JackYoungCustom = 10//可以自定义：选中和不选中view的宽度和透明度样式
}
///分页控件的位置
@objc public enum MDHCycleScrollViewPageControlAliment: Int {
    ///默认样式 中间
    case center = 0
    ///居右
    case right = 1
}


///标识
fileprivate let cellIdentifier = "MDHCycleScrollCollectionViewCell"

///DataSource 和 delegate
@objc public protocol MDHCycleScrollViewDelegate : NSObjectProtocol {
    /// 如果你需要自定义cell样式，请在实现此代理方法返回你的自定义cell的class。 */
    @objc optional func customCollectionViewCellClassFor(cycleScrollView: MDHCycleScrollView) -> (AnyClass)
    ///如果你自定义了cell样式，请在实现此代理方法为你的cell填充数据以及其它一系列设置
    @objc optional func setupCustomCell(cell: UICollectionViewCell, forIndex: Int, cycleScrollView: MDHCycleScrollView) -> Void
    
    ////** 点击图片回调 */
    @objc optional func cycleScrollView(cycleScrollView: MDHCycleScrollView, didSelectItemAt index: Int) -> Void
    ///图片滚动回调
    @objc optional func cycleScrollView(cycleScrollView: MDHCycleScrollView, didScrollTo index: Int) -> Void
    ///图片滚动回调 之前index和后面的index
    @objc optional func cycleScrollView(cycleScrollView: MDHCycleScrollView, scrollView: UIScrollView, formIndex: Int, toIndex: Int) -> Void
    //当偏移量改变时调用。进度范围是从0到最大索引值，这意味着一轮滚动的进度值
    @objc optional func cycleScrollView(cycleScrollView: MDHCycleScrollView, progress: Double) -> Void
}


/// 轮播图 参考：SDCycleScrollView 和 ZKCycleScrollView
open class MDHCycleScrollView: UIView {
    //MARK: - === 属性
    ///图片滚动方向 滑动方向 默认是 横向滑动
    @objc open var scrollDirection = UICollectionView.ScrollDirection.horizontal {
        didSet {
            if scrollDirection == .horizontal {
                self.viewCycle?.scrollDirection = .horizontal
            }else{
                self.viewCycle?.scrollDirection = .vertical
            }
        }
    }
    /// 自动滚动间隔时间,默认3s
    @objc open var autoScrollTimeInterval: Double = 3.0 {
        didSet {
            self.viewCycle?.autoScrollInterval = autoScrollTimeInterval
        }
    }
    ///设置每个Cell的大小
    @objc open var itemSize = CGSize.zero {
        didSet {
            self.viewCycle?.itemSize = itemSize
        }
    }
    ///间距 Cell的间距
    @objc open var itemSpacing: CGFloat = 0 {
        didSet {
            self.viewCycle?.itemSpacing = itemSpacing
        }
    }
    ///未命中点的不透明度
    @objc open var inactiveTransparency: CGFloat = 0.4
    ///cell的缩放
    @objc open var itemZoomScale: CGFloat = 1.0 {
        didSet {
            self.viewCycle?.itemZoomScale = itemZoomScale
        }
    }
    ///是否自动滚动,默认Yes
    @objc open var autoScroll = true {
        didSet {
            self.viewCycle?.isAutoScroll = autoScroll
        }
    }
    ///默认是。Collection是否允许拖动
    @objc open var allowsDragging = true {
        didSet {
            self.viewCycle?.allowsDragging = allowsDragging
        }
    }
    ///当前滑动到第几个视图
    @objc open var pageIndex: Int {
        get {
            return self.viewCycle?.pageIndex ?? 0
        }
    }
    ///获取当前的 偏移量
    @objc open var contentOffset: CGPoint {
        get {
            return self.viewCycle?.contentOffset ?? CGPoint.zero
        }
    }
    /** 是否无限循环,默认Yes */
    @objc open var infiniteLoop = true
    ///加载完成的回调
    @objc open var loadCompletion: VoidBlock?
    ///占位图，用于网络未加载到图片时
    @objc open var placeholderImage: UIImage? {
        didSet {
            if self.backgroundImageView == nil {
                let imv = SDAnimatedImageView()
                imv.contentMode = UIView.ContentMode.scaleAspectFit
                if let vi = self.viewCycle {
                    self.insertSubview(imv, belowSubview: vi)
                }
                self.backgroundImageView = imv
            }
            self.backgroundImageView?.image = placeholderImage
        }
    }
    ///是否只展示 文字轮播
    @objc open var onlyDisplayText = false {
        didSet {
            if onlyDisplayText && self.imageURLStringsGroup.count <= 0 {
                self.reloadData()
            }
        }
    }
    ///代理
    @objc public weak var delegate: MDHCycleScrollViewDelegate? {
        didSet {
            if let del = self.delegate, del.responds(to: #selector(del.customCollectionViewCellClassFor(cycleScrollView:))) {
                self.viewCycle?.register(del.customCollectionViewCellClassFor?(cycleScrollView: self), forCellWithReuseIdentifier: cellIdentifier)
            }
        }
    }
    /** 轮播图片的ContentMode，默认为 UIViewContentModeScaleToFill */
    @objc open var bannerImageViewContentMode = UIView.ContentMode.scaleAspectFill
    /// 轮播文字label高度  高度
    @objc open var titleLabelHeight: CGFloat = 30
    ///轮播文字label字体颜色 文本的颜色
    @objc open var titleLabelTextColor = UIColor.white
    ///轮播文字label字体大小 文本的大小
    @objc open var titleLabelTextFont = UIFont.systemFont(ofSize: 13)
    ///轮播文字label背景颜色 文本的背景颜色
    @objc open var titleLabelBackgroundColor = UIColor.black.withAlphaComponent(0.5)
    /// 轮播文字label对齐方式 文本的字体的方向
    @objc public var titleLabelTextAlignment = NSTextAlignment.left
    ///设置 cell、图片的圆角
    @objc public var cellRadiusCorner: CGFloat = 0
    
    //////////////////////  数据源API //////////////////////
    ///网络图片 url string 数组 及 Image
    @objc public var imageURLStringsGroup = [Any]() {
        didSet {
            self.reloadData()
        }
    }
    ////** 每张图片对应要显示的文字数组 */
    @objc public var titlesGroup = [Any]() {
        didSet {
            if onlyDisplayText && self.imageURLStringsGroup.count <= 0 {
                self.reloadData()
            }
        }
    }
    
    /// - ===== 分页 ===== -
    ///是否显示分页控件 分页控件 默认不隐藏
    @objc public var showPageControl = true
    ///是否在只有一张图时隐藏pagecontrol，默认为YES
    @objc public var hidesForSinglePage = true
    ///pagecontrol 样式，默认为动画样式
    @objc public var pageControlStyle = MDHCycleScrollViewPageControlStyle.jalapeno {
        didSet {
            self.setupPageControl()
        }
    }
    ///分页控件位置
    @objc public var pageControlAliment = MDHCycleScrollViewPageControlAliment.center
    ///分页控件距离轮播图的底部间距（在默认间距基础上）的偏移量
    @objc public var pageControlBottomOffset: CGFloat = 0
    ///分页控件距离轮播图的右边间距（在默认间距基础上）的偏移量
    @objc public var pageControlRightOffset: CGFloat = 0
    /** 当前分页控件小圆标颜色 */
    @objc public var currentPageDotColor = UIColor.white
    /** 其他分页控件小圆标颜色 */
    @objc public var pageDotColor = UIColor.lightGray
    ///两个按钮之间的间距
    @objc public var pageControlPadding: CGFloat = 8 {
        didSet {
            self.setupPageControl()
        }
    }
    /** 分页控件小圆标大小 */
    @objc public var pageControlDotSize = CGSize.init(width: 12, height: 12) {
        didSet {
            self.setupPageControl()
        }
    }
    /** 分页控件小圆标大小 */
    @objc public var inactivePageControlDotSize = CGSize.init(width: 12, height: 12) {
        didSet {
            self.setupPageControl()
        }
    }
    /** 分页控件小圆标大小 */
    @objc public var activePageControlDotSize = CGSize.init(width: 12, height: 12) {
        didSet {
            self.setupPageControl()
        }
    }
    ////分页控件 需要判断类型 及
    @objc public weak var pageControl: UIControl?
    /// 当imageURLs为空时的背景图
    fileprivate var backgroundImageView: UIImageView?
    ///初始化
    fileprivate var viewCycle: ZKCycleScrollView?
    
    // MARK: - Init
    public init(frame: CGRect, shouldInfiniteLoop infiniteLoop: Bool? = nil) {
        super.init(frame: frame)
        
        self.infiniteLoop = infiniteLoop ?? true
        initialization()
    }
    
    @objc override public init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///设置布局
    override open func layoutSubviews() {
        super.layoutSubviews()
        self.viewCycle?.frame = self.bounds
        
        ///分页控制器
        if self.pageControl != nil {
            let countImage = CGFloat(self.imageURLStringsGroup.count)
            var sizePage = CGSize.zero
            if self.pageControl?.isKind(of: UIPageControl.classForCoder()) ?? false {
                let pcW = self.pageControlDotSize.width*1.5*countImage
                sizePage = CGSize.init(width: pcW, height: self.pageControlDotSize.height)
            }else if self.pageControl?.isKind(of: CHIBasePageControl.classForCoder()) ?? false {
                ///感觉缺少 间距 - =
                let pcW = self.pageControlDotSize.width*countImage+(countImage-1)*self.pageControlPadding
                sizePage = CGSize.init(width: pcW, height: self.pageControlDotSize.height)
            }
            
            var pcX = (self.bounds.width-sizePage.width)/2.0
            if self.pageControlAliment == .right {
                pcX = self.bounds.width-sizePage.width-10
            }
            
            let pcY = self.bounds.height-sizePage.height-10
            
            var pageControlFrame = CGRect.init(x: pcX, y: pcY, width: sizePage.width, height: sizePage.height)
            pageControlFrame.origin.x -= self.pageControlRightOffset
            pageControlFrame.origin.y -= self.pageControlBottomOffset
            self.pageControl?.frame = pageControlFrame
            self.pageControl?.isHidden = !self.showPageControl
        }
        
        ///默认的 显示图
        if self.backgroundImageView != nil {
            self.backgroundImageView?.frame = self.bounds
        }
    }
    
    deinit {
        self.viewCycle?.removeFromSuperview()
        self.viewCycle = nil
    }
    
    /// Call -beginUpdates and -endUpdates to update layout
    /// Allows multiple scrollDirection/itemSize/itemSpacing/itemZoomScale to be set simultaneously.
    open func beginUpdates() {
        self.viewCycle?.beginUpdates()
    }
    
    open func endUpdates() {
        self.viewCycle?.endUpdates()
    }
    
    ///刷新 数据
    @objc open func reloadData() -> () {
        self.viewCycle?.reloadData()
        self.setupPageControl()
    }
    ///如果在推送或呈现新的视图控制器时，单元格卡在一半时间内，则可以在CycleScrollView所在的视图控制器的-viewWillDisplay:方法中调用此方法。
//    @objc open func adjustWhenViewWillAppear() -> () {
//        if self.numberOfItems < 2 {
//            return
//        }
//        var index = self.currentIndex()
//        if index == 1 {
//            index = self.numberOfItems-3
//        }else if index == self.numberOfItems-2 {
//            index = 2
//        }
//        let indexPath = IndexPath(item: index, section: 0)
//        let position = self.scrollPosition()
//        self.collectionView.scrollToItem(at: indexPath, at: position, animated: false)
//    }
}

///分页相关 PageControl
extension MDHCycleScrollView {
    ///更新分页
    fileprivate func updatePageControl() -> () {
        if self.pageControl != nil {
            let pc = self.pageControl as? UIPageControl
            pc?.currentPage = 0
            pc?.numberOfPages = self.imageURLStringsGroup.count
            if self.onlyDisplayText {
                pc?.numberOfPages = self.titlesGroup.count
            }
            if self.hidesForSinglePage && !self.showPageControl {///单个的时候 是否需要隐藏分页
                pc?.isHidden = (pc?.numberOfPages ?? 0) < 2
            }else{
                pc?.isHidden = !self.showPageControl
            }
        }
    }
    ///设置分页控制器
    fileprivate func setupPageControl() -> () {
        //// 重新加载数据时调整
        if self.pageControl != nil {
            self.pageControl?.removeFromSuperview()
            self.pageControl = nil
        }
        ///没有图片数据 并且只显示 文字
        if self.imageURLStringsGroup.count <= 0 || self.onlyDisplayText {
            return
        }
        ///只有一张图片时 并且允许隐藏
        if self.imageURLStringsGroup.count <= 1 && self.hidesForSinglePage {
            return
        }
        ///当前是第几个
        let indexOnPageControl = self.pageIndex
        switch self.pageControlStyle {
        case .classic:///系统的
            let pc = UIPageControl()
            pc.numberOfPages = self.imageURLStringsGroup.count
            pc.currentPageIndicatorTintColor = self.currentPageDotColor
            pc.pageIndicatorTintColor = self.pageDotColor
            pc.isUserInteractionEnabled = false
            pc.currentPage = indexOnPageControl
            self.addSubview(pc)
            self.pageControl = pc
            break
        default:
            let pds_w = self.pageControlDotSize.width
            let pds_h = self.pageControlDotSize.height
            var bpc = CHIBasePageControl()
            switch self.pageControlStyle {
            case .jalapeno:///默认情况
                let bpc1 = CHIPageControlJalapeno()
                bpc1.radius = pds_w
                bpc = bpc1
                break
            case .aleppo:
                bpc = CHIPageControlAleppo()
                break
            case .jaloro:
                let bpc1 = CHIPageControlJaloro()
                bpc1.elementWidth = pds_w
                bpc1.elementHeight = pds_h
                bpc = bpc1
                bpc.radius = 3
                break
            case .chimayo:
                bpc = CHIPageControlChimayo()
                break
            case .puya:
                bpc = CHIPageControlPuya()
                break
            case .paprika:
                bpc = CHIPageControlPaprika()
                break
            case .fresno:
                bpc = CHIPageControlFresno()
                break
            case .aji:
                bpc = CHIPageControlAji()
                break
            case .JackYoungCustom:
                let bpc1 = MDHPageControlJackYoungCustom()
                bpc1.inactiveElementWidth = self.inactivePageControlDotSize.width
                bpc1.inactiveElementHeight = self.inactivePageControlDotSize.height
                bpc1.activeElementWidth = self.activePageControlDotSize.width
                bpc1.activeElementHeight = self.activePageControlDotSize.height
                bpc = bpc1
                bpc.radius = bpc1.activeElementHeight/2.0
                bpc.inactiveTransparency = self.inactiveTransparency
                break
            default:
                break
            }
            bpc.numberOfPages = self.imageURLStringsGroup.count
            bpc.currentPageTintColor = self.currentPageDotColor
            bpc.tintColor = self.pageDotColor
            bpc.padding = self.pageControlPadding

            self.addSubview(bpc)
            self.pageControl = bpc
            break
        }
    }
}


//MARK: - ====
extension MDHCycleScrollView: ZKCycleScrollViewDataSource, ZKCycleScrollViewDelegate {
    
    ///初始化
    fileprivate func initialization() -> () {
        let vc = ZKCycleScrollView.init(frame: self.bounds, shouldInfiniteLoop: self.infiniteLoop)
        self.addSubview(vc)
        self.viewCycle = vc
        vc.register(MDHCycleScrollCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
        vc.delegate = self
        vc.dataSource = self
        vc.hidesPageControl = true
        vc.loadCompletion = {
            [weak self] in
            if let block = self?.loadCompletion {
                block()
            }
        }
    }
    
    public func cycleScrollView(_ cycleScrollView: ZKCycleScrollView, cellForItemAt index: Int) -> ZKCycleScrollViewCell {
        let cell = cycleScrollView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: index)
        
        ///当前的单元格
        let itemIndex = index
        if let del = self.delegate, del.responds(to: #selector(del.setupCustomCell(cell:forIndex:cycleScrollView:))) && del.responds(to: #selector(del.customCollectionViewCellClassFor(cycleScrollView:))) {
            del.setupCustomCell?(cell: cell, forIndex: index, cycleScrollView: self)
            return cell
        }
        let cell1 = cell as? MDHCycleScrollCollectionViewCell
        if !self.onlyDisplayText {
            ///进行复制
            let imagePath = self.imageURLStringsGroup[itemIndex]
            if imagePath is String {
                let imageName = imagePath as? String ?? ""
                if imageName.hasPrefix("http") {
                    cell1?.imageView?.sd_setImage(with: URL(string: imageName), placeholderImage: self.placeholderImage)
                }else{
                    var image = UIImage(named: imageName)
                    if image == nil {//&& (image?.size.width != 0 || image?.size.height != 0)
                        image = UIImage(contentsOfFile: imageName)
                    }
                    if image == nil {//&& (image?.size.width != 0 || image?.size.height != 0)
                        image = self.placeholderImage
                    }
                    cell1?.imageView?.image = image
                }
            }else if imagePath is UIImage {
                cell1?.imageView?.image = imagePath as? UIImage// ?? UIImage()
            }
        }
        
        if self.backgroundImageView != nil {
            self.backgroundImageView?.isHidden = true
            self.backgroundImageView?.removeFromSuperview()
            self.backgroundImageView = nil
        }
        
        let titleCount = self.titlesGroup.count
        if titleCount > 0 && itemIndex < titleCount {
            let title = self.titlesGroup[itemIndex]
            if title is String {
                cell1?.titleLabel?.text = title as? String
            }else if title is NSAttributedString {
                cell1?.titleLabel?.attributedText = title as? NSAttributedString
            }else if title is NSMutableAttributedString {
                cell1?.titleLabel?.attributedText = title as? NSMutableAttributedString
            }
            cell1?.titleLabel?.isHidden = false
        }else{
            cell1?.titleLabel?.isHidden = true
        }
        
        if !(cell1?.hasConfigured ?? false) {
            cell1?.titleLabelBackgroundColor = self.titleLabelBackgroundColor
            cell1?.titleLabelHeight = self.titleLabelHeight
            cell1?.titleLabelTextAlignment = self.titleLabelTextAlignment
            cell1?.titleLabelTextColor = self.titleLabelTextColor
            cell1?.titleLabelTextFont = self.titleLabelTextFont
            cell1?.hasConfigured = true
            cell1?.imageView?.contentMode = self.bannerImageViewContentMode
            cell1?.clipsToBounds = true
            cell1?.onlyDisplayText = self.onlyDisplayText
        }
        if self.cellRadiusCorner > 0 {
            cell.dh_cornerRadius = self.cellRadiusCorner
            cell1?.imageView?.dh_cornerRadius = self.cellRadiusCorner
        }
        return cell
    }
    
    public func numberOfItems(in cycleScrollView: ZKCycleScrollView) -> Int {
        if self.onlyDisplayText {
            return self.titlesGroup.count
        }
        return self.imageURLStringsGroup.count
    }
    
    
    public func cycleScrollView(_ cycleScrollView: ZKCycleScrollView, didSelectItemAt index: Int) {
        if let del = self.delegate, del.responds(to: #selector(del.cycleScrollView(cycleScrollView:didSelectItemAt:))) {
            del.cycleScrollView?(cycleScrollView: self, didSelectItemAt: index)
        }
    }
    
    public func cycleScrollViewDidScroll(_ cycleScrollView: ZKCycleScrollView, progress: Double) {
        if let del = self.delegate, del.responds(to: #selector(del.cycleScrollView(cycleScrollView:progress:))) {
            del.cycleScrollView?(cycleScrollView: self, progress: progress)
        }
        let style = self.pageControlStyle
        if style != .classic && style != .JackYoungCustom {
            let page1 = self.pageControl as? CHIBasePageControl
            if let page = page1 {
                page.progress = progress
            }
        }
    }
    
    public func cycleScrollView(_ cycleScrollView: ZKCycleScrollView, didScrollFromIndex fromIndex: Int, toIndex: Int) {
        if let del = self.delegate, del.responds(to: #selector(del.cycleScrollView(cycleScrollView:scrollView:formIndex:toIndex:))) {
            del.cycleScrollView?(cycleScrollView: self, scrollView: cycleScrollView.collectionView, formIndex: fromIndex, toIndex: toIndex)
        }
        let style = self.pageControlStyle
        if style == .JackYoungCustom {
            let page1 = self.pageControl as? CHIBasePageControl
            if let page = page1 {
                page.progress = Double(toIndex)
            }
        }
    }
}



///Layout
open class MDHCycleScrollViewFlowLayout: UICollectionViewFlowLayout {
    
    open var zoomScale: CGFloat = 1.0
    
    override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes: [UICollectionViewLayoutAttributes] = NSArray(array: super.layoutAttributesForElements(in: rect) ?? [], copyItems: true) as! [UICollectionViewLayoutAttributes]
        if let collectionView = collectionView {
            switch scrollDirection {
            case .vertical:
                let offset = collectionView.bounds.midY;
                let distanceForScale = itemSize.height + minimumLineSpacing;
                
                for attr in attributes {
                    var scale: CGFloat = 0.0;
                    let distance = abs(offset - attr.center.y)
                    if distance >= distanceForScale {
                        scale = zoomScale;
                    } else if distance == 0.0 {
                        scale = 1.0
                        attr.zIndex = 1
                    } else {
                        scale = zoomScale + (distanceForScale - distance) * (1.0 - zoomScale) / distanceForScale
                    }
                    attr.transform = CGAffineTransform(scaleX: scale, y: scale)
                }
            default:
                let offset = collectionView.bounds.midX;
                let distanceForScale = itemSize.width + minimumLineSpacing;

                for attr in attributes {
                    var scale: CGFloat = 0.0;
                    let distance = abs(offset - attr.center.x)
                    if distance >= distanceForScale {
                        scale = zoomScale;
                    } else if distance == 0.0 {
                        scale = 1.0
                        attr.zIndex = 1
                    } else {
                        scale = zoomScale + (distanceForScale - distance) * (1.0 - zoomScale) / distanceForScale
                    }
                    attr.transform = CGAffineTransform(scaleX: scale, y: scale)
                }
            }
        }
        return attributes
    }
    
    override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
        var point = proposedContentOffset
        if let collectionView = collectionView {
            switch scrollDirection {
            case .vertical:
                /// 计算出最终显示的矩形框
                let rect = CGRect(x: 0.0, y: point.y, width: collectionView.bounds.width, height: collectionView.bounds.height)
                /// 计算collectionView最中心点的y值
                let centerY = point.y + collectionView.bounds.size.height * 0.5
                /// 存放最小的间距值
                var minDelta = CGFloat(MAXFLOAT)
                /// 获得super已经计算好的布局属性
                if let attributes = super.layoutAttributesForElements(in: rect) {
                    for attr in attributes {
                        if abs(minDelta) > abs(attr.center.y - centerY) {
                            minDelta = attr.center.y - centerY
                        }
                    }
                }
                /// 修改原有的偏移量
                point.y += minDelta
            default:
                /// 计算出最终显示的矩形框
                let rect = CGRect(x: point.x, y: 0.0, width: collectionView.bounds.width, height: collectionView.bounds.height)
                /// 计算collectionView最中心点的y值
                let centerX = point.x + collectionView.bounds.size.width * 0.5
                /// 存放最小的间距值
                var minDelta = CGFloat(MAXFLOAT)
                /// 获得super已经计算好的布局属性
                if let attributes = super.layoutAttributesForElements(in: rect) {
                    for attr in attributes {
                        if abs(minDelta) > abs(attr.center.x - centerX) {
                            minDelta = attr.center.x - centerX
                        }
                    }
                }
                /// 修改原有的偏移量
                point.x += minDelta
            }
        }
        return point
    }
}


///CollectionCell
open class MDHCycleScrollCollectionViewCell: UICollectionViewCell {
    ///imageView
    @objc weak var imageView: UIImageView?
    ///只展示文字轮播
    @objc public var onlyDisplayText = false
    /*///文字
    @objc public var title = "" {
        didSet {
            self.titleLabel?.text = title
            if self.titleLabel?.isHidden ?? true {
                self.titleLabel?.isHidden = false
            }
            self.titleLabel?.isHidden = title.count <= 0
        }
    }
    */
    ///高度
    @objc public var titleLabelHeight: CGFloat = 0
    ///文本的颜色
    @objc public var titleLabelTextColor = UIColor.black {
        didSet {
            self.titleLabel?.textColor = titleLabelTextColor
        }
    }
    ///文本的大小
    @objc public var titleLabelTextFont = UIFont.systemFont(ofSize: 13) {
        didSet {
            self.titleLabel?.font = titleLabelTextFont
        }
    }
    ///文本的背景颜色
    @objc public var titleLabelBackgroundColor = UIColor.white {
        didSet {
            self.titleLabel?.backgroundColor = titleLabelBackgroundColor
        }
    }
    ///文本的字体的方向
    @objc public var titleLabelTextAlignment = NSTextAlignment.center {
        didSet {
            self.titleLabel?.textAlignment = titleLabelTextAlignment
        }
    }
    ///是否已经设置完成了属性
    @objc public var hasConfigured = false
    
    ///文本
    fileprivate var titleLabel: MarqueeLabel?

    
    ///初始化
    override public init(frame: CGRect) {
        super.init(frame: frame)
        ///图片
        let imv = SDAnimatedImageView()
        self.contentView.addSubview(imv)
        self.imageView = imv
        
        ///文本
        let label = MarqueeLabel()
        label.isHidden = true
        self.contentView.addSubview(label)
        self.titleLabel = label
        label.trailingBuffer = 20
        label.speed = .duration(12)
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override open func layoutSubviews() {
        super.layoutSubviews()
        if self.onlyDisplayText {
            self.titleLabel?.frame = self.bounds
        }else{
            self.imageView?.frame = self.bounds
            let titFWidth = self.bounds.width
            let titFHeight = self.titleLabelHeight
            let titFX = (self.bounds.width-titFWidth)/2.0
            let titFY = self.bounds.height-titFHeight
            self.titleLabel?.frame = CGRect.init(x: titFX, y: titFY, width: titFWidth, height: titFHeight)
        }
    }
}


